package com.dfs.parent.common.web.interceptor;


import cn.hutool.core.util.StrUtil;
import com.dfs.parent.common.core.constant.TokenConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description 拦截器
 * @Author dahong
 * @Date 2024/2/23 02:39
 */
@Slf4j
public class WebHeaderInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader(TokenConstant.DFS_TOKEN);


//        Optional<String> optional = TraceContext.getCorrelation("traceId"); // 这是你的Optional对象
//        if (optional.isPresent()) {
//            //String value = optional.get();
//            // 使用value
//            TraceContext.putCorrelation("traceId", optional.get());
//        } else {
//            // 处理Optional为空的情况
//            TraceContext.putCorrelation("traceId", TraceContext.traceId());
//        }
//        optional.orElse("default value");

        String traceId = request.getHeader("traceId");
        if (StrUtil.isNotEmpty(traceId)) {
            log.info("======WebHeaderInterceptor.traceId()=====>{}",traceId);
            TraceContext.putCorrelation("traceId", traceId);
           // TraceContext.traceId(traceId);
            log.info("======TraceContext.traceId.traceId()=====>{}",TraceContext.traceId());
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
